const { Service } = require('egg')
const cheerio = require('cheerio')
const { RSAencrypt } = require('../utils/RSA')

module.exports = class LoginService extends Service {
  /**
   * * 模拟登录，获取cookie
   * @return {setCookie: string, status: number} **
   */
  async getCookie() {
    try {
      const { ctx } = this
      // const { Cookie } = ctx.data
      // console.log('Cookie', Cookie)
      const { sid, pwd } = ctx.data

      /* * 1. 请求登录页面，获取lt，warn，execution，_eventId */
      const homeUrl = 'https://sfrz.hnfnu.edu.cn/lyuapServer/login?service=http%3A%2F%2Fjwgl.hnfnu.edu.cn%3A9080%2Feams%2Fhome.action'
      const homeRes = await ctx.curl(homeUrl, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
        },
      })
      const setCookie = homeRes.headers['set-cookie'] ? homeRes.headers['set-cookie'].map((e) => e.split(';')[0]).join(';') : ''
      const $ = cheerio.load(homeRes.data.toString())
      const lt = $('input[name=lt]').attr().value
      const warn = $('input[name=warn]').attr().value
      const execution = $('input[name=execution]').attr().value
      const _eventId = $('input[name=_eventId]').attr().value

      /* * 2. 请求登录接口 */
      // eslint-disable-next-line max-len
      const password = RSAencrypt(pwd, '00ab14000dddff4fe76335bc5fb6c662ba7fa862a59421dad3c0fc3c4385c9f8c55b2dcdc4879bc9ca64cc9b169bc5393861b014ca1d74da163b8967a7116dff28bee61a02043499e155b3da45e4c4d19841d99a97584ca802d2696207110aacd5318dbe4e1b515c4af661c78ee53178aecff939fa5e74d41cf209056c380ca22d')
      const loginUrl = 'https://sfrz.hnfnu.edu.cn/lyuapServer/login?service=http%3A%2F%2Fjwgl.hnfnu.edu.cn%3A9080%2Feams%2Fhome.action'
      const loginRes = await ctx.curl(loginUrl, {
        method: 'POST',
        data: {
          username: sid,
          captcha: '',
          password,
          warn,
          lt,
          execution,
          _eventId,
        },
        headers: {
          Cookie: setCookie,
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
        },
      })
      if (loginRes.status !== 302) { return { setCookie: '', status: loginRes.status } }

      /**
       * * 3. 登录验证成功，第一次重定向
       */
      const reUrl1 = loginRes.headers.location
      console.log('reUrl1', reUrl1)
      const res1 = await ctx.curl(reUrl1, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
        data: {
          ticket: 'ST-656491-cJi63c4cbiPyaeet0zCM-cas01.example.org',
        },
      })
      let resultCookie = res1.headers['set-cookie'] ? res1.headers['set-cookie'].map((e) => e.split(';')[0]).join(';') : ''
      if (loginRes.status !== 302) { return { setCookie: '', status: loginRes.status } }

      /* * 4. 登录验证成功，第二次重定向 */
      const reUrl2 = res1.headers.location
      console.log('reUrl2', reUrl2)
      const res2 = await ctx.curl(reUrl2, {
        method: 'GET',
        headers: {
          Cookie: resultCookie,
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
      })
      // console.log('res2.headers[\'set-cookie\']', res2.headers['set-cookie'].map((e) => e.split(';')[0]).join(';'))
      resultCookie = res2.headers['set-cookie'] ? `${resultCookie};${res2.headers['set-cookie'].map((e) => e.split(';')[0]).join(';')}` : resultCookie
      if (res2.status !== 200) { return { setCookie: '', status: loginRes.status } }
      /* end */

      // return { setCookie: Cookie, status: loginRes.status }
      // console.log('setCookie', setCookie)
      return { setCookie: resultCookie, status: loginRes.status }
    } catch (err) {
      console.log(err)
      return { setCookie: '', status: 500 }
    }
  }
}
